<?php
class PaymController extends Controller
{
	//根据微信发送的信息生成签名
	protected function wxMakeSign($arr)
	{
		//排序
		ksort($arr);
		//格式化参数格式化成url参数
		$buff = "";
		foreach ($arr as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		$buff = trim($buff, "&");
		$string = $buff."&key=2c9c78581eb6002bb67c791a2a9bf667";//累加api支付秘钥
		$string = md5($string);
		$result = strtoupper($string);
		return $result;
	}
	
	public function index()
	{
		$model = new Model();
		
		//支付返回字符串
		$str=Req::args("str");
		//支付类型id
		$payment_id=intval(Req::args("payment_id"));
		
		if($payment_id === 8)//微信支付
		{
			$arr=unserialize(urldecode($str));
			//签名验证
			if($this->wxMakeSign($arr) === $arr['sign'])
			{
				if($arr['result_code'] ==="SUCCESS")
				{
					$order_no=$arr['out_trade_no'];//获取订单号
					$callback_info['trade_no']=$arr['transaction_id'];//微信交易号
					
					//---------------------------------------------------------------
					//在notifyurl方法里面判断该订单是否为合并订单号
					$demo_order_obj = $model->table("demo_order")->where("order_no='{$order_no}'")->find();
					//为合并订单
					if(!empty($demo_order_obj))
					{
						//改变合并订单的订单状态
						//$model->table("demo_order")->data(array("status"=>'1'))->where("order_no='{$order_no}'")->update();
						$model->query("update zyk_demo_order set status=1 where order_no='{$order_no}'");
						//改变子订单的订单状态
						$demo_arr = explode(",", $demo_order_obj['child_order_no']);
						for($i=0; $i < count($demo_arr); $i++)
						{
						    $payment_id = 5;
							Order::updateStatus($demo_arr[$i], $payment_id, $callback_info);
						}
						echo 'success';
					}
					//为正常订单
					else 
					{
					    $payment_id = 5;
					    if(Order::updateStatus($order_no, $payment_id, $callback_info))
					    {
					        echo 'success';
					    }
					    else
					    {
					        echo 'fail';
					    }
						/*
						$orderObj = $model->table("order")->where("order_no='{$order_no}'")->find();
						if(intval($orderObj['classify_flag']) === 1)//如果为积分支付专区
						{
							//不产生任何奖金记录
							//更改订单状态
							//更改商品库存
							//将支付数据插入收款表
							if($this->change_point_order_status($order_no, $payment_id))
							{
								//根据订单金额减去相应的用户账户积分余额
								$model->table("user")->data(array('point'=>"`point`-".$orderObj['order_amount']))->where("id=".$orderObj['user_id'])->update();
								$post_money = $orderObj['post_money'];
								//记录日志
								Log::balance((0-$post_money),$orderObj['user_id'],'积分兑换专区，通过微信邮费方式进行商品购买,订单编号：'.$orderObj['order_no']);
							}
							echo 'success';
						}
						else 
						{
							if(Order::updateStatus($order_no, $payment_id, $callback_info))
							{
								echo 'success';
							}
							else 
							{
								echo 'fail';
							}
						}
						*/
					}
				}
				else 
				{
					echo 'fail';
				}
			}
			else 
			{
				echo 'fail';
			}
			
		}
		
		if($payment_id === 9)//支付宝即时到账
		{
			$arr=unserialize(urldecode($str));
			
			if($arr['trade_status'] == 'TRADE_FINISHED')
			{
				
		    }
		    elseif ($arr['trade_status'] == 'TRADE_SUCCESS')
		    {
		    	$order_no=$arr['out_trade_no'];//获取订单号
				$callback_info['trade_no']=$arr['trade_no'];//支付宝交易号
				
				//---------------------------------------------
				//在notifyurl方法里面判断该订单是否为合并订单号
				$demo_order_obj = $model->table("demo_order")->where("order_no='{$order_no}'")->find();
				//为合并订单
				if(!empty($demo_order_obj))
				{
					//改变合并订单的订单状态
					//$model->table("demo_order")->data(array("status"=>'1'))->where("order_no='{$order_no}'")->update();
					$model->query("update zyk_demo_order set status=1 where order_no='{$order_no}'");
					//改变子订单的订单状态
					$demo_arr = explode(",", $demo_order_obj['child_order_no']);
					for($i=0; $i < count($demo_arr); $i++)
					{
					    $payment_id = 4;
						Order::updateStatus($demo_arr[$i], $payment_id, $callback_info);
					}
					echo 'success';
				}
				//为正常订单
				else 
				{
				    
				    if(Order::updateStatus($order_no, $payment_id, $callback_info))
				    {
				        echo 'success';
				    }
				    else
				    {
				        echo 'fail';
				    }
				    
				    /*
					$orderObj = $model->table("order")->where("order_no='{$order_no}'")->find();
					if(intval($orderObj['classify_flag']) === 1)//如果为积分支付专区
					{
						//不产生任何奖金记录
						//更改订单状态
						//更改商品库存
						//将支付数据插入收款表
						if($this->change_point_order_status($order_no, $payment_id))
						{
							//根据订单金额减去相应的用户账户积分余额
							$model->table("user")->data(array('point'=>"`point`-".$orderObj['order_amount']))->where("id=".$orderObj['user_id'])->update();
							$post_money = $orderObj['post_money'];
							//记录日志
							Log::balance((0-$post_money),$orderObj['user_id'],'积分兑换专区，通过支付宝 移动 即时到账支付邮费方式进行商品购买,订单编号：'.$orderObj['order_no']);
						}
						echo 'success';
					}
					else 
					{
						if(Order::updateStatus($order_no, $payment_id, $callback_info))
						{
							echo 'success';
						}
						else 
						{
							echo 'fail';
						}
					}
					*/
					
				}
				//-------------------------------------------------
				
				
				
		    }
		    
		}
		
		if($payment_id === 1)//奖金账户支付
		{
			//传递过来的参数就是订单号
			$order_no = $str;
			//----------------------------------------------------------
			//在notifyurl方法里面判断该订单是否为合并订单号
			$demo_order_obj = $model->table("demo_order")->where("order_no='{$order_no}'")->find();
			//为合并订单
			if(!empty($demo_order_obj))
			{
				//改变合并订单的订单状态
				//$model->table("demo_order")->data(array("status"=>'1'))->where("order_no='{$order_no}'")->update();
				$model->query("update zyk_demo_order set status=1 where order_no='{$order_no}'");
				
				//改变子订单的订单状态
				$demo_arr = explode(",", $demo_order_obj['child_order_no']);
				
				for($i=0; $i < count($demo_arr); $i++)
				{
					if(Order::updateStatus($demo_arr[$i], $payment_id))
					{
						//更改订单买家的账户余额，以及记录日志
						$this->change_balance($demo_arr[$i], $payment_id);
					}
				}
				echo 'success';
			}
			else 
			{
				$orderObj = $model->table("order")->where("order_no='{$order_no}'")->find();
				if(intval($orderObj['classify_flag']) === 1)//如果为积分支付专区
				{
					//不产生任何奖金记录
					//更改订单状态
					//更改商品库存
					//将支付数据插入收款表
					if($this->change_point_order_status($order_no, $payment_id))
					{
						//$post_money = $orderObj['post_money'];
						
						//更改账户余额
						$model->table("user")->data(array('balance'=>"`balance`-".$orderObj['order_amount']))->where("id=".$orderObj['user_id'])->update();
						//根据订单金额减去相应的用户账户积分余额
						$model->table("user")->data(array('point'=>"`point`-".$orderObj['order_amount']))->where("id=".$orderObj['user_id'])->update();
						
						//记录日志
						Log::balance((0-$orderObj['order_amount']),$orderObj['user_id'],'积分兑换专区，通过余额支付邮费方式进行商品购买,订单编号：'.$orderObj['order_no']);
					}
				}
				else 
				{
					if(Order::updateStatus($order_no, $payment_id))
					{
						$this->change_balance($order_no, $payment_id);
					}
				}
				echo 'success';
			}
			
			
		}
		
		
		if($payment_id === 10)//消费充值账户支付
		{
			//传递过来的参数就是订单号
			$order_no = $str;
			//----------------------------------------------------------
			//在notifyurl方法里面判断该订单是否为合并订单号
			$demo_order_obj = $model->table("demo_order")->where("order_no='{$order_no}'")->find();
			//为合并订单
			if(!empty($demo_order_obj))
			{
				//改变合并订单的订单状态
				//$model->table("demo_order")->data(array("status"=>'1'))->where("order_no='{$order_no}'")->update();
				$model->query("update qc_demo_order set status=1 where order_no='{$order_no}'");
				
				//改变子订单的订单状态
				$demo_arr = explode(",", $demo_order_obj['child_order_no']);
				
				for($i=0; $i < count($demo_arr); $i++)
				{
					if(Order::updateStatus($demo_arr[$i], $payment_id))
					{
						//更改订单买家的账户余额，以及记录日志
						$this->change_balance($demo_arr[$i], $payment_id);
					}
				}
				echo 'success';
			}
			else 
			{
				$orderObj = $model->table("order")->where("order_no='{$order_no}'")->find();
				if(intval($orderObj['classify_flag']) === 1)//如果为积分支付专区
				{
					//不产生任何奖金记录
					//更改订单状态
					//更改商品库存
					//将支付数据插入收款表
					if($this->change_point_order_status($order_no, $payment_id))
					{
						//$post_money = $orderObj['post_money'];
						
						//更改账户余额
						$model->table("user")->data(array('balance'=>"`balance`-".$orderObj['order_amount']))->where("id=".$orderObj['user_id'])->update();
						//根据订单金额减去相应的用户账户积分余额
						$model->table("user")->data(array('point'=>"`point`-".$orderObj['order_amount']))->where("id=".$orderObj['user_id'])->update();
						
						//记录日志
						Log::balance((0-$orderObj['order_amount']),$orderObj['user_id'],'积分兑换专区，通过余额支付邮费方式进行商品购买,订单编号：'.$orderObj['order_no']);
					}
				}
				else 
				{
					if(Order::updateStatus($order_no, $payment_id))
					{
						$this->change_balance($order_no, $payment_id);
					}
				}
				echo 'success';
			}
			
			
		}
		
		
		if($payment_id === 11)//贵宾增值账户支付
		{
			//传递过来的参数就是订单号
			$order_no = $str;
			//----------------------------------------------------------
			//在notifyurl方法里面判断该订单是否为合并订单号
			$demo_order_obj = $model->table("demo_order")->where("order_no='{$order_no}'")->find();
			//为合并订单
			if(!empty($demo_order_obj))
			{
				//改变合并订单的订单状态
				//$model->table("demo_order")->data(array("status"=>'1'))->where("order_no='{$order_no}'")->update();
				$model->query("update qc_demo_order set status=1 where order_no='{$order_no}'");
				
				//改变子订单的订单状态
				$demo_arr = explode(",", $demo_order_obj['child_order_no']);
				
				for($i=0; $i < count($demo_arr); $i++)
				{
					if(Order::updateStatus($demo_arr[$i], $payment_id))
					{
						//更改订单买家的账户余额，以及记录日志
						$this->change_balance($demo_arr[$i]);
					}
				}
				echo 'success';
			}
			else 
			{
				$orderObj = $model->table("order")->where("order_no='{$order_no}'")->find();
				if(intval($orderObj['classify_flag']) === 1)//如果为积分支付专区
				{
					//不产生任何奖金记录
					//更改订单状态
					//更改商品库存
					//将支付数据插入收款表
					if($this->change_point_order_status($order_no, $payment_id))
					{
						//$post_money = $orderObj['post_money'];
						
						//更改账户余额
						$model->table("user")->data(array('balance'=>"`balance`-".$orderObj['order_amount']))->where("id=".$orderObj['user_id'])->update();
						//根据订单金额减去相应的用户账户积分余额
						$model->table("user")->data(array('point'=>"`point`-".$orderObj['order_amount']))->where("id=".$orderObj['user_id'])->update();
						
						//记录日志
						Log::balance((0-$orderObj['order_amount']),$orderObj['user_id'],'积分兑换专区，通过余额支付邮费方式进行商品购买,订单编号：'.$orderObj['order_no']);
					}
				}
				else 
				{
					if(Order::updateStatus($order_no, $payment_id))
					{
						$this->change_balance($order_no,$payment_id);
					}
				}
				echo 'success';
			}
			
			
		}
		
	}
	
	protected function change_balance($order_no, $payment_id)
	{
		$model = new Model();
		$orderObj=$model->table("order")->fields("user_id,order_amount")->where("order_no='{$order_no}'")->find();
		//用户id
		$user_id = $orderObj['user_id'];
				 				  
		$total_fee = $orderObj['order_amount'];//订单金额
		//更改用户账户余额
		if($payment_id === 1)
		{
			$data=array('balance'=>"`balance`-$total_fee");//奖金账户
			$str="奖金账户";
		}
		elseif($payment_id === 10)
		{
			$data=array('xfcz_account'=>"`xfcz_account`-$total_fee");//消费充值账户
			$str="消费充值账户";
		}
		elseif($payment_id === 11)
		{
			$data=array('gbzz_account'=>"`gbzz_account`-$total_fee");//贵宾增值账户
			$str="贵宾增值账户";
		}
		$flag = $model->table("user")->data($data)->where("id=".$user_id)->update();
		if($flag)
		{	
			//记录支付日志
            Log::balance((0-$total_fee),$user_id,"通过{$str}支付方式进行商品购买,订单编号：".$order_no);
		}
	}
	
	//积分兑换商品后，改变订单状态
	//以及将数据插入收款表
	protected function change_point_order_status($orderNo,$payment_id=0,$callback_info=null)
	{
		$model = new Model("order");
		$order = $model->where("order_no='".$orderNo."'")->find();
		if(isset($callback_info['trade_no'])) $trading_info = $callback_info['trade_no'];
		else $trading_info = '';
		if(empty($order)) return false;
		if($order['pay_status']==1)
		{
			return $order['id'];
		}
		else if($order['pay_status']==0)
		{
			//更新订单信息
			$data = array(
				'status'     => 3,
				'pay_time'   => date('Y-m-d H:i:s'),
				'trading_info'=>$trading_info,
				'pay_status' => 1,
			);
			//修改用户最后选择的支付方式
			if($payment_id!=0){
				$data['payment'] = $payment_id;
			}else{
				$payment_id = $order['payment'];
			}
			//更新订单支付状态
			$model->table("order")->data($data)->where("id=".$order['id'])->update();
			
		
			$products = $model->table("order_goods")->where("order_id=".$order['id'])->findAll();
			$goods_ids = array();
			foreach ($products as $pro) {
				//更新货品中的库存信息
				$goods_nums = $pro['goods_nums'];
				$product_id = $pro['product_id'];
				$model->table("products")->where("id=".$product_id)->data(array('store_nums'=>"`store_nums`-".$goods_nums))->update();
				$goods_ids[$pro['goods_id']] = $pro['goods_id'];
			}
			//更新商品表里的库存信息
			foreach ($goods_ids as $id) {
				$objs = $model->table('products')->fields('sum(store_nums) as store_nums')->where('goods_id='.$id)->query();
				if($objs){
					$num = $objs[0]['store_nums'];
					$model->table('goods')->data(array('store_nums'=>$num))->where('id='.$id)->update();
				}
			}
			
			//生成收款单
			$receivingData = array(
				'order_id'=>$order['id'],
				'user_id'=>$order['user_id'],
				'amount'=>$order['order_amount'],
				'cb'=>$order['hjcb'],
				'create_time'=>date('Y-m-d H:i:s'),
				'payment_time'=>date('Y-m-d H:i:s'),
				'doc_type'=>0,
				'payment_id'=>$payment_id,
				'pay_status'=>1
			);
			$model->table("doc_receiving")->data($receivingData)->insert();
			return $order['id'];
		}
		else
		{
			return false;
		}
	}
	
}
?>